package com.sgb.knowledgeshare.weight;
import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.aliyun.utils.NetWatchdog;
import com.apeng.permissions.EsayPermissions;
import com.apeng.permissions.OnPermission;
import com.sgb.knowledgeshare.R;
import com.sgb.knowledgeshare.ShareConfig;
import com.sgb.knowledgeshare.view.activity.VideoReportActivity;
import com.swgk.core.base.model.entity.H5ReEntity;
import com.swgk.core.base.model.entity.VideoBean;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.RoundCornerDialog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.util.ThreadUtils;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 分享-分享底部弹窗实现
 */
public class ShareDialog {
    private ImageView sixins, dingdings, weixins, savefiles, informs;
    private TextView cancels;
    private LinearLayout llInform, llDelete;
    private static File file;
    private String url;

    public ShareDialog(Activity Context, int attype, VideoBean videoData) {
        getShareAppUrl(Context,videoData);
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(Context, R.style.RoundCornerDialog);
        //2、设置布局
        View view = View.inflate(Context, R.layout.share_dialog, null);
        sixins = view.findViewById(R.id.sixin);
        dingdings = view.findViewById(R.id.dingding);
        weixins = view.findViewById(R.id.weixin);
        savefiles = view.findViewById(R.id.save_file);
        informs = view.findViewById(R.id.inform);
        cancels = view.findViewById(R.id.cancel);
        llInform = view.findViewById(R.id.ll_inform);
        llDelete = view.findViewById(R.id.ll_delete);
            if (videoData.getCreateUser().equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, ""))) {
                llDelete.setVisibility(View.VISIBLE);
                llInform.setVisibility(View.GONE);
            } else {
                llDelete.setVisibility(View.GONE);
                llInform.setVisibility(View.VISIBLE);
            }
        dialog.setContentView(view);
        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.BOTTOM);
        //设置弹出动画
        window.setWindowAnimations(R.style.ActionSheetDialogAnimation);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();
        //        私信
        sixins.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
        // 钉钉
        dingdings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                ShareConfig.getInstance().getInstance().startShareData(Context, videoData.getTypeName() + " " + videoData.getTitle(),url,videoData.getCover(), 2);
            }
        });
        //微信
        weixins.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                ShareConfig.getInstance().getInstance().startShareData(Context, videoData.getTypeName() + " " + videoData.getTitle(),url,videoData.getCover(), 1);
            }
        });
        //报存到相册
        savefiles.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ThreadUtils.runOnSubThread(new Runnable() {
                    @Override
                    public void run() {
                        String videosize = FileSizeUtils(videoData.getCoverURL());
                        ThreadUtils.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
                                if (Build.VERSION.SDK_INT > 25) {
                                    //6.0以上运行时权限处理
                                    EsayPermissions.with(Context).constantRequest().permission(permissions).request(new OnPermission() {
                                        @Override
                                        public void hasPermission(List<String> granted, boolean isAll) {
                                            if (isAll) {
                                                //判断网络是否是4G网络（用阿里云的utils方法）
                                                boolean gConnected = NetWatchdog.is4GConnected(Context);
                                                if (gConnected) {//当前网络为4G时走提示弹窗下载方法
                                                    ThreadUtils.runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            DownloadvideoDialog(Context, videosize, videoData);
                                                        }
                                                    });

                                                } else {//当前网络为wifi时直接下载
                                                    //有所有权限
                                                    UpDataInfo(Context, videoData);
                                                }

                                            } else {
                                                MToast.showToast(Context, "获取权限失败");
                                            }
                                        }

                                        @Override
                                        public void noPermission(List<String> denied, boolean quick) {
                                            if (quick) {
                                                MToast.showToast(Context, "被永久拒绝授权，请手动授予权限");
                                                //如果是被永久拒绝就跳转到应用权限系统设置页面
                                                EsayPermissions.gotoPermissionSettings(Context);
                                            } else {
                                                MToast.showToast(Context, "获取权限失败");
                                            }
                                        }
                                    });
                                } else {
                                    //判断网络是否是4G网络（用阿里云的utils方法）
                                    boolean gConnected = NetWatchdog.is4GConnected(Context);
                                    if (gConnected == true) {//当前网络为4G时走提示弹窗下载方法
                                        ThreadUtils.runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                DownloadvideoDialog(Context, videosize, videoData);
                                            }
                                        });
                                    } else {//当前网络为wifi时直接下载
                                        //有所有权限
                                        UpDataInfo(Context, videoData);
                                    }
                                }
                                dialog.dismiss();
                            }
                        });
                    }
                });
            }
        });
        //举报
        informs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                VideoReportActivity.start(Context, videoData.getVideoId());
            }
        });
        // 取消
        cancels.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
//        删除视频的操作
        llDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                OnDeleteVideo.OnDeleteVideoData(videoData.getId());
            }
        });

    }

    //获取视频分享的url链接地址
    public void getShareAppUrl(Activity context, VideoBean videoData) {
        ShareConfig.getInstance().getApi().getUrlSetting("knowledges").enqueue(new Callback<BaseEntity<H5ReEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<H5ReEntity>> call, Response<BaseEntity<H5ReEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(ShareConfig.RESPONSE_OK)) {
                    if (!TextUtils.isEmpty(response.body().getData().getUrl())){
                        url = response.body().getData().getUrl()+"?videoId="+videoData.getVideoId();
                    }
                } else {
                    MToast.showToast(context, response.body().getMsg());
                }
            }
            @Override
            public void onFailure(Call<BaseEntity<H5ReEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();

            }
        });
    }

    //获取文件大小
    public String FileSizeUtils(String coverURL) {
        URL url = null;
        try {
            url = new URL(coverURL);
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) url.openConnection();
            //处理下载读取长度为-1 问题
            conn.setRequestProperty("Accept-Encoding", "identity");
            conn.connect();
            // 获取文件大小
            int length = conn.getContentLength();
            if (length < 1024) { //b
                return length + "B";
            } else if (length < 1048576) {//kb
                return length / 1024 + "KB";
            } else if (length < 1073741824) {  //mb
                return length / 1048576 + "MB";
            } else { //gb
                return length / 1073741824 + "GB";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "0B";
    }

    //下载确认弹窗
    private void DownloadvideoDialog(Activity context, String videoSize,VideoBean videoData) {

        View view = View.inflate(context, R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(context, 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        TextView tvtitle = view.findViewById(R.id.tv_title);
        TextView tv_message = view.findViewById(R.id.tv_message);
        TextView tv_logout_cancel = view.findViewById(R.id.tv_logout_cancel);
        TextView tv_logout_confirm = view.findViewById(R.id.tv_logout_confirm);
        tvtitle.setText("下载确认");
        tv_logout_cancel.setText("取消");
        tv_logout_cancel.setTextColor(context.getResources().getColor(R.color.color_blue_0888ff));
        tv_logout_confirm.setText("继续下载");
        tv_logout_confirm.setTextColor(context.getResources().getColor(R.color.color_blue_0888ff));
        tv_message.setText("正在使用非 WIFI网络，下载视频预计消耗" + videoSize + "流量");
        //继续下载
        tv_logout_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                roundCornerDialog.dismiss();
                //有所有权限
                UpDataInfo(context, videoData);
            }
        });
        tv_logout_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                roundCornerDialog.dismiss();
            }
        });
    }

    public OnDeleteVideo OnDeleteVideo;

    public interface OnDeleteVideo {
        void OnDeleteVideoData(int VideoId);
    }

    public void setOnDeleteVideo(OnDeleteVideo OnDeleteVideo) {
        this.OnDeleteVideo = OnDeleteVideo;
    }

    //下载视频
    private void UpDataInfo(Activity context, VideoBean videoData) {
        final ProgressDialog pd;
        pd = new ProgressDialog(context);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("正在下载...");
        pd.getWindow().setGravity(Gravity.CENTER_HORIZONTAL);
        pd.setCanceledOnTouchOutside(false);
        pd.setProgressNumberFormat("%1d Mb /%2d Mb");//这里设置的是进度条下面显示的文件大小和下载了多
        pd.show();
        //这里就是权限打开之后自己要操作的逻辑
        new Thread() {
            @Override
            public void run() {
                try {
                    if (videoData != null && !TextUtils.isEmpty(videoData.getCoverURL())) {
                        File file = VideoDownload(context, videoData, pd);
                        updataImage(context, file);//通知系统更新图库信息
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private void updataImage(Activity context, File file) {
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
    }

    //   视频下载
    private File VideoDownload(Activity context, VideoBean videoData, ProgressDialog pd) throws Exception {
        //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            URL url = null;
            url = new URL(videoData.getCoverURL());
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            pd.setMax(conn.getContentLength() / (1024 * 1024));
            InputStream is = conn.getInputStream();
            file = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".mp4");
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            int total = 0;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                total += len;
                pd.setProgress(total / (1024 * 1024));
            }
            fos.close();
            bis.close();
            is.close();
            pd.dismiss();
            ThreadUtils.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    MToast.showToast(context, "保存视频成功！");
                }
            });
            return file;
        } else {
            ThreadUtils.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    MToast.showToast(context, "保存视频失败！");
                }
            });
            return null;
        }
    }



}